/**
 * Created by admin on 2017/12/13.
 */

define([
    "helpers/network",
    "models/roles",
    "models/administrator",
    "views/modules/popup",
    "views/modules/form",
    "views/modules/table",
    "views/modules/pager",
    "libs/md5",
    "libs/editor/ueditor.all"
], function (Network,Roles, ModelAdmin, PopupView, CommonForm, CommonTable, CommonPager,Md5) {

    var TYPE = "Info";
    var id = "";
    var windowsId = id + "window";
    var keywordsId = id + "keywordsId";
    var queryPrerequisiteId = id + "queryPrerequisiteId";
    var accountStatusId = id + "accountStatusId";
    var searchFormId = id + "searchForm";
    var formId = id + "form";
    var tableId = id + "table";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var groupIdsData = [];
    var pageIndex = 1;

    var onTableReady = function (page) {
        var searchForm = $$(searchFormId).getValues();
        var obj = {
            params: {

                keyWord:searchForm[keywordsId] ? searchForm[keywordsId] : undefined,
                statuss:searchForm[accountStatusId] ? searchForm[accountStatusId].split(",")  :undefined,
            },
            size :20,
            page: page,
            sort: ["creationTime,desc"]
        };
        Network.ajax("/AdminView.queryAll.query", obj, function (ret) {
            Network.ajax("/AdminGroupView.queryAll.query", {params:{},all:true}, function (ret) {
                groupIdsData = ret.data.content;
            });
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            CommonPager.refreshPager(page, ret.data.totalPages);
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + ret.data.totalPages + "页");
        });
        pageIndex = page ? page : 1
    };

    var onWindowReady = function (item) {

    };

    var closeWindow = function () {
        if ($$(windowsId)) {
            $$(windowsId).close();
        }
    };

    var getData = function () {
        var data = []
        console.log(groupIdsData)
        for(var i= 0; i<groupIdsData.length; i++ ){
            data.push({id:groupIdsData[i].id,value:groupIdsData[i].name})
        }
        console.log(data)
        return data
    }

    var onSubmit = function (itemValues) {
        if(!itemValues){
            webix.message("请选择一个要修改的项！");
            return
        }
        var ajaxUrl = itemValues.id ? "/AdminTransactor.update.command" : "/AdminTransactor.create.command"
        itemValues.lastModifyTime = new Date();
        itemValues["status"]=itemValues.status.id
        itemValues["type"]=itemValues.type.id
        var groupIds = itemValues.groupIds.id
        itemValues["groupIds"]=groupIds ? [groupIds] : undefined;
        var obj ={data: itemValues};
        Network.ajax(ajaxUrl, obj, function (ret) {
            //设置密码
            if(itemValues.password.length <20){
                Network.ajax("/AdminTransactor.updatePassword.command", {data:{id:ret.data,password:Md5(itemValues.password)}}, function (ret) {

                })
            }
            closeWindow();
            webix.message("添加成功")
            onTableReady(pageIndex);
        })
    };

    //状态修改
    var updateStatus = function (item) {
        if(!item){
            webix.message("请选择要操作的项！");
            return
        }
        var ajaxUrl = item.status == "Enable" ? "/AdminTransactor.disableAdmin.command" : "/AdminTransactor.enableAdmin.command"
        var obj ={
            data:{
            id:item.id
            }
        }
        Network.ajax(ajaxUrl, obj, function () {
            onTableReady(pageIndex)
            webix.message("操作成功！")
        })
    }

    var showWindow = function (title, item) {
        item = item || {data: {}};
        PopupView(windowsId, title, {
            rows: [
                {
                    view: "scrollview", scroll: "y", paddingY: 5, paddingX: 10,
                    body: {
                        rows: [
                            {
                                view: "form", borderless: true, id: formId,
                                elements: [
                                    {
                                        label: "id", name: "id", view: "text", hidden:true,
                                        required: true, value: item.id || ""
                                    },
                                    {
                                        label: "登录名", name: "username", view: "text",
                                        required: true, value: item.username || ""
                                    },
                                    {
                                        label: "登录密码", name: "password", view: "text",
                                        type:"password",
                                        required: true, value: item.password || ""
                                    },
                                    {
                                        label: "用户名称", name: "staff", view: "text",
                                        required: true, value: item.staff || ""
                                    },
                                    // {
                                    //     label: "qq", name: "qq", view: "text",
                                    //     required: true, value: item.qq || ""
                                    // },
                                    {
                                        label: "手机号", name: "mobile", view: "text",
                                        required: true, value: item.mobile || ""
                                    },
                                    {
                                        label: "身份证号", name: "idCardNo", view: "text",
                                        required: true, value: item.idCardNo || ""
                                    },
                                    // {
                                    //     label: "微信", name: "weixin", view: "text",
                                    //     required: true, value: item.weixin || ""
                                    // },
                                    // {
                                    //     label: "邮箱", name: "email", view: "text",
                                    //     required: true, value: item.email || ""
                                    // },
                                    CommonForm.genSingleOptionSelector("groupIds", "管理组", getData(function () {}), item["groupIds"] ? item["groupIds"] :[] , false),
                                    CommonForm.genSingleOptionSelector("status", "状态", ModelAdmin.adminStatus, item["status"], true),
                                    CommonForm.genSingleOptionSelector("type", "角色", ModelAdmin.accountType, item["type"], true),
                                    {}
                                ]
                            }]
                    }
                },
                CommonForm.genSubmitButton(function () {
                    if (!$$(formId).validate()) {
                        webix.message("信息填写有误, 请仔细录入...");
                        return
                    }
                    var itemValues = $$(formId).getValues();
                    onSubmit(itemValues)
                })
            ]
        }, 600, 570, function () {
            onWindowReady(item)
        }, closeWindow);
    };

    //删除管理员
    var deleteBrand = function (item) {
            var obj = {
                data: {
                    id: item.id
                }
            }
            Network.ajax("/AdminTransactor.delete.command", obj, function (data) {
                closeWindow();
                webix.message("删除成功")
                onTableReady(pageIndex);
            })
    }

    var genSearchFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                id: searchFormId, view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {},
                    // {
                    //     id: "static", name: "static", view: "select", width: 80, css: {"text-align": "center"},
                    //     value: "mobile",
                    //     options: ModelAdmin.adminSearchTypes
                    // },
                    CommonForm.genKeywordsUI(keywordsId, "依据用户ID/手机号码/真实姓名/用户名进行查询", onTableReady),
                    CommonForm.genMultiOptionsSelector(accountStatusId, "账号状态", ModelAdmin.accountStatus, _.map(ModelAdmin.accountStatus, 'id').join(",")),
                    CommonForm.genQueryButtonUI(onTableReady)
                ]
            }
        }
    };

    var genOperationFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {view: "label", label: "操作"},
                    {
                        view: "button", label: "添加", width: 90,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            showWindow("添加")
                        }
                    },
                    {
                        view: "button", label: "修改", width: 90,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            var item = $$("table").getSelectedItem();
                            if (!item) {
                                webix.message("请选择一个要修改的项！");
                                return
                            }
                            showWindow("修改", item)
                        }
                    },
                    {
                        id: "enableShopBtn",
                        view: "button", label: "禁用/启用", width: 90,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            var item = $$("table").getSelectedItem();
                            updateStatus(item);
                        }
                    },
                    // {
                    //     view: "button", label: "删除", width: 90, type: "danger",
                    //     // hidden: ,
                    //     click:function () {
                    //         //获取选中元素
                    //         var item = $$("table").getSelectedItem();
                    //         if(! item){
                    //             webix.message("请选择要删除的项...！")
                    //             return
                    //         }
                    //         deleteBrand(item)
                    //     }
                    // },
                ]
            }
        }
    };

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, select: "row", data: [],
            complexData: true,
            ready: onTableReady,
            on: {
                onItemClick: function (id) {
                    var item = this.getItem(id);
                    if (item.status === "Disable") {
                        $$("enableShopBtn").define("label", "启用")
                    } else if (item.status === "Enable") {
                        $$("enableShopBtn").define("label", "禁用")
                    }
                    $$('enableShopBtn').refresh();
                }
            },
            columns: [
                {
                    id: "id", header: "ID"
                },
                {
                    id: "username", header: "姓名", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "idCardNo", header: "身份证号", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "vTypeText", header: "角色", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "vStatusText", header: "状态", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "remark", header: "备注", fillspace: true,
                    // template: "#data.remark#"
                },
                {
                    id: "creationTime", header: "创建时间", fillspace: true,
                    // template: "#data.remark#"
                }
            ]
        }
    };

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    return {
        $ui: {
            padding: 10,
            rows: [
                genSearchFormUI(),
                genOperationFormUI(),
                genDataTableUI(),
                genFooterUI()
            ]
        }
    };

});